package go_prometheus_basic_data

import (
	"github.com/shirou/gopsutil/cpu"
	"github.com/shirou/gopsutil/disk"
	"github.com/shirou/gopsutil/mem"
	"time"
)

const (
	B  = 1
	KB = 1024 * B
	MB = 1024 * KB
	GB = 1024 * MB
)

type Cpu struct {
	Cpus        []float64 `json:"cpus"`
	Cores       int       `json:"cores"`
	UsedPercent float64   `json:"used_percent"`
}

type Ram struct {
	UsedMB      int     `json:"usedMb"`
	TotalMB     int     `json:"totalMb"`
	UsedPercent float64 `json:"used_percent"`
}

type Disk struct {
	UsedMB      int     `json:"usedMb"`
	UsedGB      int     `json:"usedGb"`
	TotalMB     int     `json:"totalMb"`
	TotalGB     int     `json:"totalGb"`
	UsedPercent float64 `json:"used_percent"`
}

//@function: GetCPU
//@description: CPU信息
//@return: c Cpu, err error

func GetCPU() (c Cpu, err error) {
	var (
		cpuNum float64
	)
	if cores, err := cpu.Counts(false); err != nil {
		return c, err
	} else {
		c.Cores = cores
	}
	if cpus, err := cpu.Percent(time.Duration(200)*time.Millisecond, true); err != nil {
		return c, err
	} else {
		c.Cpus = cpus
	}
	for i := 0; i < len(c.Cpus); i++ {
		cpuNum += c.Cpus[i]
	}
	if len(c.Cpus) > 0 {
		c.UsedPercent = cpuNum / float64(len(c.Cpus))
	}
	return c, nil
}

//@function: InitRAM
//@description: RAM信息
//@return: r Ram, err error

func GetRAM() (r Ram, err error) {
	if u, err := mem.VirtualMemory(); err != nil {
		return r, err
	} else {
		r.UsedMB = int(u.Used) / MB
		r.TotalMB = int(u.Total) / MB
		r.UsedPercent = u.UsedPercent
	}
	return r, nil
}

//@function: InitDisk
//@description: 硬盘信息
//@return: d Disk, err error

func GetDisk() (d Disk, err error) {
	if u, err := disk.Usage("/"); err != nil {
		return d, err
	} else {
		d.UsedMB = int(u.Used) / MB
		d.UsedGB = int(u.Used) / GB
		d.TotalMB = int(u.Total) / MB
		d.TotalGB = int(u.Total) / GB
		d.UsedPercent = u.UsedPercent
	}
	return d, nil
}
